<template>
  <a-modal
    :visible="visible"
    :title="!$isEmpty(propsData) ? '修改接收人员' : '添加接收人员'"
    @ok="handleSubmit"
    @cancel="handleClose"
  >
    <a-form :form="form">
      <a-form-item label="姓名">
        <a-input
          v-decorator="['LevelUserStation', { rules: [{ required: true, message: '请输入姓名' }] }]"
          placeholder="请输入姓名"
        />
      </a-form-item>
      <a-form-item label="类型电话">
        <a-input
          v-decorator="[
            'phone',
            {
              rules: [
                { required: true, message: '', whitespace: true, trigger: 'change' },
                { validator: validatePhone },
              ],
            },
          ]"
          placeholder="请输入类型电话"
        />
      </a-form-item>
    </a-form>
  </a-modal>
</template>

<script>
/**
 *Parser
 *@Author
 *@Version
 *@property
 *@event
 */
import { validTelphone } from '@/utils/validate'
export default {
  props: {
    defaultValue: {
      type: Array,
      default: () => []
    },
    propsData: {
      type: Object,
      default: () => {}
    },
    visible: {
      type: Boolean,
      default: false
    }
  },
  watch: {
    visible (n) {
      if (n) {
        this.fetchData()
      }
    }
  },
  data () {
    return {
      isSubmiting: false,
      form: this.$form.createForm(this, { name: 'smsFormUser' })
    }
  },
  methods: {
    fetchData () {
      if (!this.$isEmpty(this.propsData)) {
        const { LevelUserStation, phone } = this.propsData
        this.$nextTick(() => {
          this.form.setFieldsValue({
            LevelUserStation,
            phone
          })
        })
      }
    },
    validatePhone (rule, value, callback) {
      if (!value) {
        callback(new Error('请输入您的联系电话!'))
      }
      if (!validTelphone(value)) {
        callback(new Error('联系电话输入有误，请重新输入!'))
      }
      if (this.defaultValue.find((e) => e.phone === value) && this.propsData.phone !== value) {
        callback(new Error('存在相同电话号码，请检查已添加数据！'))
      }
      callback()
    },
    handleSubmit () {
      this.form.validateFields((err, values) => {
        if (!err) {
          this.$emit('success', {
            type: this.$isEmpty(this.propsData) ? 'add' : 'edit',
            data: Object.assign(
              {
                LevelDeptID: this.propsData.LevelDeptID || '',
                LevelDeptName: this.propsData.LevelDeptName || '',
                LevelUserID: this.propsData.LevelUserID || ''
              },
              values
            )
          })
          this.handleClose()
        }
      })
    },
    handleClose () {
      this.form.resetFields()
      this.$emit('update:visible', false)
    }
  }
}
</script>
<style scoped></style>
